package com.cxs.service.impl;

import com.cxs.dto.LoginUserDTO;
import com.cxs.mapper.UsersMapper;
import com.cxs.model.Users;
import com.cxs.model.UsersExample;
import com.cxs.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cxs.utils.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/10/2  20:26
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public PageInfo<Users> selectList(Integer pageNum, Integer pageSize, String keyWord) {
        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 5;
        PageHelper.startPage(pageNum, pageSize);
        List<Users> userList = usersMapper.selectAll(keyWord);
        return new PageInfo<>(userList);
    }

    @Override
    public Result login(LoginUserDTO userDTO) {
        UsersExample example = new UsersExample();
        UsersExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(userDTO.getUsername());
        List<Users> list = usersMapper.selectByExample(example);
        if(list.size() > 0){
            Users users = list.get(0);
            if (userDTO.getPassword().trim().equals(users.getPassword())) {
                if(users.getStatus() == 1){
                    Users userObj = usersMapper.selectOne(users.getId());
                    return Result.OK("登陆成功",userObj);
                }
                else  return Result.failare("登陆失败，账户已冻结");
            }else return Result.failare("登录失败,密码错误");
        }else {
            return Result.failare("登陆失败,用户名不存在!");
        }
    }

    @Override
    public Result update(Users user) {
        return usersMapper.updateByPrimaryKeySelective(user) > 0 ? Result.OK("修改成功") : Result.failare("修改失败");
    }

    @Override
    public Result del(Long id) {
        return usersMapper.deleteByPrimaryKey(id) > 0 ? Result.OK("删除成功") : Result.failare("删除失败");
    }

    @Override
    public Result blukdel(List<Long> ids) {
        Integer result = usersMapper.deleteByBlukIds(ids);
        return result > 0 ? Result.OK("删除成功",result) : Result.failare("删除失败");
    }

    @Override
    public Users findUserByUsername(String username) {
        UsersExample example = new UsersExample();
        UsersExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(username);
        List<Users> users = usersMapper.selectByExample(example);
        if(users.size() > 0){
            return users.get(0);
        }else{
            return null;
        }

    }
}
